package com.julyup.core.controller;

import com.julyup.core.redis.RedisLock;
import com.julyup.core.util.ResponseObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Author: zhenzhong.wang@honeywell.com
 * @Date: 2019/4/25 12:52 PM
 */
@RestController
public class RedisLockController {

  @GetMapping("/api/lock")
  public ResponseObject hcCompany() throws InterruptedException {
    System.out.println("尝试获取redis锁...");
    while (!RedisLock.tryLock("key_name", 10)) {
      System.out.println("尝试获取锁失败，睡眠1s");
      TimeUnit.SECONDS.sleep(1);
    }
    RedisLock.releaseLock("key_name");

    return ResponseObject.success(null);
  }

  @GetMapping("/api/releaseLock")
  public ResponseObject hcCompany2() throws InterruptedException {
    System.out.println("\n尝试释放redis锁...");
    if (RedisLock.releaseLock("key_name")) {
      System.out.println("锁释放成功");
    } {
      System.out.println("释放失败");
    }
    return null;
  }

}
